package com.duoec.dw.lineage.service.analyser.expr;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import com.duoec.dw.lineage.dto.TableFieldLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import com.duoec.dw.lineage.service.HiveAnalyser;
import com.duoec.dw.lineage.service.analyser.HiveExprAnalyser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashSet;

/**
 * @author xuwenzhen
 */
public abstract class BaseExprAnalyser<T extends SQLExpr> implements HiveExprAnalyser<T> {
    @Autowired
    protected HiveAnalyser hiveAnalyser;

    public void setHiveAnalyser(HiveAnalyser hiveAnalyser) {
        this.hiveAnalyser = hiveAnalyser;
    }

    protected LinkedHashSet<TableFieldDependencyDto> getDependencies(
            @NonNull TableLineageDto table, @Nullable TableFieldLineageDto field, String fieldName
    ) {
        LinkedHashSet<TableFieldDependencyDto> dependencies = new LinkedHashSet<>();
        LinkedHashSet<TableFieldDependencyDto> globalDependencies = table.getDependencies();
        if (globalDependencies != null) {
            dependencies.addAll(globalDependencies);
        }
        if (field != null) {
            LinkedHashSet<TableFieldDependencyDto> fieldDependencies = field.getDependencies();
            if (!CollectionUtils.isEmpty(fieldDependencies)) {
                dependencies.addAll(fieldDependencies);
                return dependencies;
            }

            if (field.getValuable()) {
                return dependencies;
            }
        }

        //手工添加当前字段依赖
        TableFieldDependencyDto fieldDependency = new TableFieldDependencyDto();
        fieldDependency.setDatabaseName(table.getDatabaseName());
        fieldDependency.setTableName(table.getTableName());
        fieldDependency.setFieldName(fieldName);
        dependencies.add(fieldDependency);

        return dependencies;
    }
}
